<template>
  <div class="min-h-screen bg-gray-50 p-8">
    <h1 class="text-2xl font-bold mb-6">测试头像上传</h1>
    
    <div class="bg-white p-6 rounded-lg shadow-md max-w-md mx-auto">
      <form @submit.prevent="uploadAvatar" class="space-y-4">
        <div>
          <label class="block text-sm font-medium text-gray-700">选择图片</label>
          <input 
            type="file" 
            ref="fileInput" 
            @change="handleFileChange" 
            accept="image/*"
            class="mt-1 block w-full py-2 px-3 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm"
          />
        </div>
        
        <div v-if="previewUrl" class="mt-4">
          <h3 class="text-sm font-medium text-gray-700 mb-2">预览</h3>
          <div class="h-40 w-40 rounded-full bg-cover bg-center mx-auto" :style="`background-image: url('${previewUrl}')`"></div>
        </div>
        
        <div>
          <button 
            type="submit" 
            class="w-full py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-primary hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary"
            :disabled="!selectedFile || uploading"
          >
            {{ uploading ? '上传中...' : '上传' }}
          </button>
        </div>
      </form>
      
      <div v-if="result" class="mt-6 p-4 rounded-md" :class="result.success ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'">
        {{ result.message }}
        <div v-if="result.success && result.avatar" class="mt-2">
          <p class="text-sm mb-1">上传后的地址:</p>
          <pre class="bg-gray-100 p-2 rounded text-xs overflow-auto">{{ result.avatar }}</pre>
          <div class="mt-2 h-16 w-16 rounded-full bg-cover bg-center mx-auto" :style="`background-image: url('${result.avatar}')`"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useAuthStore } from '@/stores/auth';
import axios from 'axios';

const authStore = useAuthStore();
const fileInput = ref<HTMLInputElement | null>(null);
const selectedFile = ref<File | null>(null);
const previewUrl = ref<string | null>(null);
const uploading = ref(false);
const result = ref<{ success: boolean; message: string; avatar?: string } | null>(null);

// 处理文件选择
function handleFileChange(event: Event) {
  const input = event.target as HTMLInputElement;
  if (input.files && input.files[0]) {
    selectedFile.value = input.files[0];
    
    // 创建预览
    const reader = new FileReader();
    reader.onload = (e) => {
      previewUrl.value = e.target?.result as string;
    };
    reader.readAsDataURL(input.files[0]);
  }
}

// 上传头像
async function uploadAvatar() {
  if (!selectedFile.value) return;
  
  uploading.value = true;
  result.value = null;
  
  try {
    const formData = new FormData();
    formData.append('avatar', selectedFile.value);
    
    console.log('Token:', authStore.token);
    console.log('开始上传头像', selectedFile.value.name, selectedFile.value.type);
    
    const { data } = await axios.post('/api/users/avatar', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': `Bearer ${authStore.token}`
      }
    });
    
    console.log('上传响应:', data);
    
    // 成功结果
    result.value = {
      success: true,
      message: '头像上传成功!',
      avatar: data.avatar
    };
    
    // 更新用户信息中的头像
    if (authStore.user) {
      authStore.user.avatar = data.avatar;
      localStorage.setItem('user', JSON.stringify(authStore.user));
    }
  } catch (error: any) {
    console.error('上传失败:', error);
    
    // 错误结果
    result.value = {
      success: false,
      message: error.response?.data?.message || '头像上传失败，请重试'
    };
  } finally {
    uploading.value = false;
  }
}
</script> 